<template>
  <view class="tui-skeleton relative" @click="hideList">
    <view id="top" ref="top">
      <view v-if="type" class="flex-row padding-30">
        <picker mode="selector" class="picker" :value="searchProductIndex" :range="productList" range-key="name"
                @change="bindSearchProduct">
          <view class="product-box flex-row align-center">
            <view class="flex-item">
              <text class="text-24 color-t1 text-overflow-one">{{ productList[searchProductIndex].name }}</text>
            </view>
            <!-- #ifndef APP-PLUS -->
            <text class="tbb-arrow-down flex-row flex-center text-24 color-t1 margin-right-8"/>
            <!-- #endif -->
            <!-- #ifdef APP-PLUS -->
            <text class="iconfont flex-row flex-center text-24 color-t1 margin-right-8">&#xe687;</text>
            <!-- #endif -->
          </view>
        </picker>
        <!--        <tui-button text="设定全部价格" width="186rpx" height="64rpx" border-radius="8rpx" :size="28" :shadow="false" @click="setAllPrice" />-->
      </view>
      <template v-else>
        <car-filter ref="filter" :type-label="typeLabel" @changeDate="changeDate" @changeStatus="changeStatus"
                    @showList="show = $event"/>
        <view class="padding-30">
          <top-search v-model="number" placeholder="搜索车牌号" text="新增车辆" @clear="clearSearch" @confirm="reload"
                      @click="addNew"/>
        </view>
      </template>
    </view>

    <view v-if="list.length" class="flex-column" :style="{height:height-topHeight+'px'}" @click="hideList">
      <!-- #ifndef APP-NVUE -->
      <scroll-view
          v-if="list.length>0"
          class="flex-column flex-item"
          :scroll-top="top"
          :style="{height:height-topHeight+'px'}"
          :refresher-triggered="refresh"
          lower-threshold="100"
          refresher-enabled
          enable-back-to-top
          scroll-y
          @scrolltolower="nextPage"
          @refresherrefresh="refresherrefresh"
      >
        <view class="flex-column">
          <view v-for="(item, index) in list" :key="index">
            <product-item v-if="type" :item="item" :margin-top="index ? '30rpx' : '0'"/>
            <car-item v-else :item="item" :choose-year="chooseYear" :margin-top="index ? '30rpx' : '0'" @more="more"
                      @showAction="showAction"/>
          </view>
        </view>
        <l-footer :has-more="hasMore"/>
      </scroll-view>
      <!-- #endif -->
      <!-- #ifdef APP-NVUE -->
      <list v-if="list.length>0" ref="list" class="flex-column flex-item" :show-scrollbar="false" :offset-accuracy="5"
            loadmoreoffset="100" :bounce="false" fix-freezing="true">
        <cell v-for="(item, index) in list" :key="index">
          <product-item v-if="type" :item="item" :margin-top="index ? '30rpx' : '0'"/>
          <car-item v-else :item="item" :choose-year="chooseYear" :margin-top="index ? '30rpx' : '0'" @more="more"
                    @showAction="showAction"/>
        </cell>
        <cell @appear="nextPage">
          <l-footer :has-more="hasMore"/>
        </cell>
      </list>
      <!-- #endif -->
    </view>

    <view v-else :style="{height:height-topHeight+'px'}">
      <tui-skeleton v-if="showSkeleton" :preload-data="preloadData"/>
      <l-no-data v-else text="暂无数据" type="data"/>
    </view>

    <car-types v-if="!type" :show="show" @choose="chooseType"/>

    <view v-if="noPermission" class="no-permission">
      <l-no-data type="permission" text="暂无权限"/>
    </view>
  </view>
</template>

<script>
import CarFilter from '../car-filter/car-filter'
import CarItem from '../car-item/car-item'
import ProductItem from '../product-item/product-item'
import CarTypes from '../car-types/car-types'
import request from '@/common/api/request'
import {mapGetters} from 'vuex'
import {jump, getElementInfo} from '@/common/util'
import {vehicleStatusSearch, getProductPriceList, getProductList} from '@/common/api/car'
import {vehiclePreloadData, productPreloadData} from './index'

export default {
  name: 'CarPage',
  components: {
    CarFilter,
    CarItem,
    ProductItem,
    CarTypes
  },
  props: {
    type: {
      type: Number,
      default: 0
    },
    height: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      list: [],
      hasMore: true,
      top: 0,
      refresh: false,
      showSkeleton: true,
      page: 1,
      topHeight: 0,
      pageSize: 9999,
      noPermission: false,
      /* page1*/
      status: '',
      number: '',
      typeId: '',
      selDate: '',
      autoBrand: '',
      seatAmount: '',
      show: false,
      typeLabel: '',
      /* page2*/
      productList: [
        {name: ''}
      ],
      searchProductId: '',
      searchProductIndex: 0,
      defaultPrice: 1
    }
  },
  computed: {
    preloadData() {
      return this.type ? productPreloadData : vehiclePreloadData
    },
    chooseYear() {
      return this.selDate.slice(0, 4)
    },
    ...mapGetters({
      auth: 'auth'
    })
  },
  watch: {
    height() {
      this.getHeight()
    }
  },
  created() {
    this.setAuth()
    if (this.type) this.getAllProductList()
  },
  methods: {
    setAuth() {
      if (!this.type && !this.auth.includes('vehicle_view')) this.noPermission = true
      if (this.type && !this.auth.includes('product_view')) this.noPermission = true
    },
    getHeight() {
      getElementInfo('#top', res => {
        this.topHeight = res.height
      }, this)
    },
    // 获取列表
    async getList() {
      let list
      if (this.type === 0) list = await this.getVehicleStatusList()
      if (this.type === 1) list = await this.getProductPriceList()

      if (list.length < this.pageSize) this.hasMore = false
      if (this.page === 1) this.list = list
      else this.list.push(...list)
    },
    // 获取车态列表
    async getVehicleStatusList() {
      const [err, res] = await vehicleStatusSearch({
        status: this.status,
        numberOrDriverName: this.number,
        typeId: this.typeId,
        page: this.page,
        limit: this.pageSize,
        startDate: this.selDate,
        autoBrand: this.autoBrand,
        seatAmount: this.seatAmount
      })
      uni.stopPullDownRefresh()
      this.refresh = false
      if (!request.errorCheck(err, res)) return false
      let list = res.data.data.records
      if (!list) list = []
      // 获取车态地点名
      list.forEach(item => {
        if (item.dayStatusList) {
          item.dayStatusList.forEach(dayStatus => {
            if (dayStatus.eventList) {
              dayStatus.eventList.forEach(event => {
                event.startPlace = event.start ? event.start.split('|')[0] : ''
                event.endPlace = event.end ? event.end.split('|')[0] : ''
              })
            }
          })
        }
      })
      this.showSkeleton = false
      return list
    },
    // 获取产品列表
    async getProductPriceList() {
      const [err, res] = await getProductPriceList({
        productId: this.searchProductId,
        vehicleTypeId: 0,
        page: this.page,
        limit: this.pageSize,
        defaultPrice: this.defaultPrice
      })
      uni.stopPullDownRefresh()
      this.refresh = false
      this.showSkeleton = false
      if (!request.errorCheck(err, res)) return false
      let list = res.data.data
      if (!list) list = []
      return list
    },
    // 刷新
    reload() {
      this.hasMore = true
      this.page = 1
      this.getList()
    },
    refresherrefresh() {
      this.refresh = true
      this.reload()
    },
    // 下一页
    nextPage() {
      if (this.hasMore) {
        this.page++
        this.getList()
      }
    },
    // 清除列表
    clear() {
      this.page = 1
      this.list = this.list.slice(0, this.pageSize * this.page)
      this.top = this.top ? 0 : 1
    },
    /* page1*/
    // 更多按钮
    more(e) {
      this.$emit('more', e)
    },
    // 车态点击事件
    showAction(e) {
      this.$emit('showAction', e)
    },
    // 清空搜索
    clearSearch() {
      this.number = ''
      this.reload()
    },
    // 添加新车辆
    addNew() {
      jump('/vehicle/add-vehicle/add-vehicle')
    },
    // 修改日期
    changeDate(e) {
      this.selDate = e
      this.reload()
    },
    changeStatus(e) {
      this.status = e
      this.reload()
    },
    hideList() {
      if (!this.type) {
        this.$refs.filter.show = false
        this.show = false
      }
    },
    chooseType(e) {
      console.log(3333, e)
      this.autoBrand = e.autoBrand || ''
      this.seatAmount = e.seatAmount || ''
      this.typeId = e.value
      this.typeLabel = e.label
      console.log(this.typeLabel, this.productList)
      this.reload()
    },
    /* page1 end*/

    /* page2*/
    // 获取产品列表
    async getAllProductList() {
      const [err, res] = await getProductList({
        current: 1,
        size: 9999,
        type: 0
      })
      if (!request.errorCheck(err, res)) return false
      this.productList = res.data.data.filter(e => e.type != 8)

      this.searchProductId = this.productList[this.searchProductIndex].id
      this.reload()
    },
    // 筛选产品
    bindSearchProduct(e) {
      const val = e.detail.value
      this.searchProductIndex = val
      this.searchProductId = this.productList[val].id
      this.reload()
    },
    setAllPrice() {
      jump('/vehicle/set-all-price/set-all-price?id=' + this.searchProductId)
    }
    /* page2 end*/
  }
}
</script>

<style scoped lang="scss">
@include setMargin(right, 24);

.picker {
  //width:480rpx;
  width: 100%;
}

.product-box {
  height: 64 rpx;
  border-radius: 8 rpx;
  background: $font-color-white;
  padding: 0 16 rpx;
}

.no-permission {
  @include position(fixed, 0, 0, 0, 0);
  background: $color-background;
}
</style>
